package com.fei.config;

import com.fei.bean.AdminBean;
import com.fei.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class AdminRealm extends AuthorizingRealm {

    @Autowired
    AdminService adminService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();

        AdminBean adminBean = (AdminBean)subject.getPrincipal();//获取登录时admin的对象

        //给出对应的权限
        if(adminBean.getRole() == 1){
            info.addStringPermission("admin:addUpdate");
        }else if(adminBean.getRole() == 2){
            info.addStringPermission("admin:addUpdate");
            info.addStringPermission("admin:delete");
        }

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken adminToken = (UsernamePasswordToken)token;
        //传入一个管理员的名字查询，查询是否有该管理员
        AdminBean admin = adminService.selectOneNameService(adminToken.getUsername());

        if(admin == null){
            return null;
        }

        //存入session
        Subject cureentSubject = SecurityUtils.getSubject();
        Session session = cureentSubject.getSession();
        session.setAttribute("admin",admin);

        return new SimpleAuthenticationInfo(admin,admin.getPassword(),"");
    }

}
